package hbsi.edu.demo2;

/**
 * @author 程奕红
 * @version 1.0
 */



import java.sql.*;
import java.util.Scanner;

/**
 * @author 程奕红
 * @version 1.0
 */
public class TestUser2 {
    public static void main(String[] args) throws SQLException {
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入用户名");
        String name=scanner.nextLine();
        System.out.println("请输入密码");
        String pass=scanner.nextLine();
        login2(name,pass);
    }

    public  static  void login2(String name,String pass) throws SQLException {
        Connection connection=null;
        PreparedStatement statement=null;
        ResultSet res=null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url="jdbc:mysql:///myjdbc";
            String username="root";
            String password="root";
            connection= DriverManager.getConnection(url,username,password);

            String sql="select * from users where name=? and password=?";
            statement=connection.prepareStatement(sql);

            statement.setString(1,name);//2是根据变量在sql语句中的位置
            statement.setString(2,pass);
            res=statement.executeQuery();
            if(res.next()){
                System.out.println("登录成功");
            }else{
                System.out.println("登陆失败，请检查用户名或密码！");
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }finally {
            if(res!=null){
                res.close();
            }if(statement!=null){
                statement.close();
            }if(connection!=null){
                connection.close();
            }

        }

    }
}
